import { constantRouterMap } from '@/config/router'
import { BasicLayout, RouteView } from '@/layouts'
import { asyncRouterHandle } from '@/utils/asyncRouter'
function handelRouter (router) {
  if (router.children && router.children.length !== 0) {
    router.children.map(item => {
      handelRouter(item)
    })
  }
  if (router.component === 'BasicLayout') {
    router.component = BasicLayout
  } else if (router.component === 'RouteView') {
    router.component = RouteView
  } else {
    router.component = asyncRouterHandle(router.component)
  }
  return router
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },

  actions: {
    GenerateRouters ({ commit, state }, data) {
      return new Promise(resolve => {
        const routerList = []
        routerList.push(handelRouter(data[0]))
        const route404 = {
          path: '*',
          redirect: '/404',
          hidden: true
        }
        routerList.push(route404)
        commit('SET_ROUTERS', routerList)
        resolve()
      })
    }
  }
}

export default permission
